package com.example.ymm.config;

import com.alibaba.fastjson.JSONObject;
import com.example.ymm.bo.YmUserDetails;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.UserLogin;
import com.example.ymm.model.em.EmLoginPlatform;
import com.example.ymm.util.JwtTokenUtil;
import com.example.ymm.util.RedisKeyManager;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@Slf4j
public class AuthorInterceptor implements HandlerInterceptor {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;
//	@Value("${jwt.tokenHeader}")
	private String tokenHeader="Authorization";
//	@Value("${jwt.tokenHead}")
	private String tokenHead="Bearer";
	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 这个方法的主要作用是用于清理资源的，当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
	{
		// TODO Auto-generated method stub

	}

	/**
	 * 在Controller的方法调用之后执行
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws IOException{

	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		CommonResult<JSONObject> jsonObject = CommonResult.unLogin();
		String authHeader = request.getHeader(this.tokenHeader);
		if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
			String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
			String username = jwtTokenUtil.getUserNameFromToken(authToken.trim());
			String userId = jwtTokenUtil.getUserIdFromToken(authToken.trim());
			Integer platform = jwtTokenUtil.getPlatformFromToken(authToken.trim());
			if (userId != null) {

				UserLogin userLogin=null;
				String s = "";

				if(platform== EmLoginPlatform.pc_3.getType()){
					s = redisUtil.get(RedisKeyManager.pc_token_key + authToken,String.class);
				}
				if(platform!= EmLoginPlatform.pc_3.getType()){
					s = redisUtil.get(RedisKeyManager.user_token_key+userId+":" + authToken,String.class);
				}
				if(UtilValidate.isNotEmpty(s)){
					userLogin = JSONObject.parseObject(s,UserLogin.class);
					YmUserDetails userDetails =new YmUserDetails(userLogin);
					if (jwtTokenUtil.validateToken(authToken, userDetails)) {
						UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
						authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
						log.info("authenticated user:{}", username);
						SecurityContextHolder.getContext().setAuthentication(authentication);
						return true;
					}
				}

			}
		}

		makeResult(response, renderJson(jsonObject));
		return false;
	}

	private void makeResult(HttpServletResponse response, JSONObject jo) {
		response.setContentType("application/json; charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		try (PrintWriter out = response.getWriter()) {
			out.append(jo.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private JSONObject renderJson(Object o) {
		return JSONObject.parseObject(JSONObject.toJSONString(o));
	}

}
